package com.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.dto.OrdersDTO;
import com.demo.dto.R;
import com.demo.entity.*;
import com.demo.service.*;
import com.demo.util.MyPage;
import com.demo.vo.MedicineVO;
import com.demo.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * (Orders)表控制层
 *
 * @author Sakura
 * @since 2023-11-26 17:11:07
 */
@Api(value = "/api/orders", tags = {"(Orders)表控制层"})
@RestController
@RequestMapping("/api/order")
@CrossOrigin
public class OrdersController {
    /**
     * 服务对象
     */
    @Resource
    private OrdersService ordersService;
    @Resource
    private OrderCardService orderCardService;
    @Resource
    private CardService cardService;
    @Resource
    private CardMedicineService cardMedicineService;
    @Resource
    private MedicineService medicineService;

    /**
     * 分页查询
     *
     * @param pageNo   当前页
     * @param pageSize 数据大小
     * @param uid      商家id
     * @return 查询结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageNo", value = "当前页", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageSize", value = "数据大小", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "uid", value = "查询参数")
    })
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "GET")
    @GetMapping("/list/{pageNo}/{pageSize}/{uid}")
    public R<MyPage<OrdersDTO>> queryByPage(@PathVariable Integer pageNo,
                                            @PathVariable Integer pageSize,
                                            @PathVariable(required = false) Long uid) {
        return R.success(this.ordersService.queryByPage(pageNo, pageSize, uid));
    }

    /**
     * 通过主键查询药品列表
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "通过主键查询药品列表", notes = "通过主键查询药品列表", httpMethod = "GET")
    @GetMapping("{id}")
    public R queryById(@PathVariable("id") Long id) {
        return R.success(ordersService.getMedicineListById(id));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "删除数据", notes = "删除数据", httpMethod = "DELETE")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Long id) {
        boolean result = this.ordersService.removeById(id);
        if (!result) {
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }

    @PutMapping("/cancel/{oid}")
    public R getById(@PathVariable("oid") long oid) {
        Orders order = ordersService.getById(oid);
        order.setCancel(1);
        boolean update = ordersService.updateById(order);
        if (!update) {
            return R.error("取消失败,请重新尝试");
        }
        return R.success("取消成功");
    }


    //通过用户id获取订单
    @GetMapping("/{userId}/{cancel}")
    public R queryByUserId(@PathVariable("userId") Long userId,@PathVariable("cancel") int cancel) {
//    public R queryByUserId(@PathVariable("userId") Long userId) {
//        System.out.println(cancel);
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Orders::getUserId, userId);
        lambdaQueryWrapper.orderByDesc(Orders::getCreateTime);
        lambdaQueryWrapper.eq(cancel!=-1,Orders::getCancel,cancel);
        List<Orders> list = ordersService.list(lambdaQueryWrapper);
//        Page page1 = ordersService.page(page, lambdaQueryWrapper);

        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders orders : list) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orders.getCreateTime()));
            LambdaQueryWrapper<OrderCard> orderCardWrapper = new LambdaQueryWrapper();
            orderCardWrapper.eq(OrderCard::getOrderId, orders.getId());
            List<OrderCard> list1 = orderCardService.list(orderCardWrapper);
            List<MedicineVO> medicineVOS = new ArrayList<>();
            for (OrderCard orderCard : list1) {
                LambdaQueryWrapper<Medicine> medicineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                medicineLambdaQueryWrapper.eq(Medicine::getId, orderCard.getMedicineId());
                Medicine medicine = medicineService.getOne(medicineLambdaQueryWrapper);
                MedicineVO medicineVO = new MedicineVO();
                medicineVO.setId(medicine.getId());
                medicineVO.setCount(orderCard.getNum());
                medicineVO.setImage(medicine.getImage());
                medicineVO.setName(medicine.getName());
                medicineVO.setPrice(medicine.getPrice());
                medicineVO.setAttrsText(medicine.getContent());
                medicineVOS.add(medicineVO);
            }
            orderVO.setMedicineVOS(medicineVOS);
            orderVOS.add(orderVO);
        }
        return R.success(orderVOS);
    }

    @PostMapping("/Audit")
    public R Audit(@RequestBody Orders orders) {
        orders.setStatus("1");
        this.ordersService.updateById(orders);
        return R.success("成功");
    }

    @PostMapping("/cancel")
    public R cancel(@RequestBody Orders orders) {
        orders.setCancel(1);
        this.ordersService.updateById(orders);
        return R.success("成功");
    }

    @PutMapping("/agree/{oid}")
    public R agree(@PathVariable Long oid) {
        Orders orders = ordersService.getById(oid);
        orders.setStatus("2");
        boolean update = this.ordersService.updateById(orders);
        if (!update) {
            return R.error("审核失败,请重新尝试");
        }
        return R.success("审核成功");
    }

    @PutMapping("/finished/{oid}")
    public R finished(@PathVariable Long oid) {
        Orders orders = ordersService.getById(oid);
        orders.setCancel(2);
        boolean update = this.ordersService.updateById(orders);
        if (!update) {
            return R.error("失败,请重新尝试");
        }
        return R.success("成功");
    }
    @PutMapping("/rejected/{oid}")
    public R rejected(@PathVariable Long oid) {
        Orders orders = ordersService.getById(oid);
        orders.setStatus("3");
        boolean update = this.ordersService.updateById(orders);
        if (!update) {
            return R.error("驳回失败,请重新尝试");
        }
        return R.success("驳回成功");
    }
    @GetMapping("/createOrder")
    public R createOrder(@RequestParam long id) {
        System.out.println(id);
        LambdaQueryWrapper<Card> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Card::getUserId,id);
        Card card = cardService.getOne(lambdaQueryWrapper);
        List<CardMedicine> cardMedicines=new ArrayList<>();
        if (card!=null){
            LambdaQueryWrapper<CardMedicine> cardMedicineQueryWrapper=new LambdaQueryWrapper();
            cardMedicineQueryWrapper.eq(CardMedicine::getCardId,card.getId());
            cardMedicineQueryWrapper.eq(CardMedicine::getSelected,1);
            cardMedicines = cardMedicineService.list(cardMedicineQueryWrapper);
        }
        double price=0.0;
        boolean flag=false;
        long uuid= getUUID();
        for (CardMedicine cardMedicine : cardMedicines) {
            Medicine medicine = medicineService.getById(cardMedicine.getMedicineId());
            price+=medicine.getPrice()*cardMedicine.getSum();
            if (medicine.getIsPrescription()==1){
                flag=true;
            }
            OrderCard orderCard=new OrderCard();
            orderCard.setOrderId(uuid);
            orderCard.setMedicineId(medicine.getId());
            orderCard.setNum(cardMedicine.getSum());
            orderCardService.save(orderCard);
            LambdaQueryWrapper<CardMedicine> cardMedicineLambdaQueryWrapper=new LambdaQueryWrapper<>();
            cardMedicineLambdaQueryWrapper.eq(CardMedicine::getMedicineId,medicine.getId());
            CardMedicine one = cardMedicineService.getOne(cardMedicineLambdaQueryWrapper);
            cardMedicineService.deleteById(one.getId());
        }
        Orders orders = new Orders();
        orders.setId(uuid);
        orders.setUserId(id);
        orders.setPrice(price);
        orders.setCreateTime(new Date());
        orders.setStatus(flag?"0":"2");
        orders.setCancel(0);
        ordersService.save(orders);
        if (flag){
            return R.success("订单包含处方药，请前往我的订单上传处方审核");
        }else {
            return R.success("下单成功");
        }
    }

    public static long getUUID() {
        String id =null;
        UUID uuid = UUID.randomUUID();
        id = uuid.toString();

        //去掉随机ID的短横线
        id = id.replace("-", "");

        //将随机ID换成数字
        int num = id.hashCode();
        //去绝对值
        num = num < 0 ? -num : num;

        id = String.valueOf(num);

        return Long.parseLong(id);
    }

}
